package com.example.e_comm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.e_comm.entity.Permission;
import com.example.e_comm.entity.Role;
import com.example.e_comm.service.PermissionService;
import com.example.e_comm.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/role")
@RequiredArgsConstructor
public class RoleController {

    @Autowired
    private RoleService roleService;
    private final PermissionService permissionService;

    @GetMapping("/page")
    public ResponseEntity<IPage<Role>> page(@RequestParam(defaultValue = "1") Integer current,
                                            @RequestParam(defaultValue = "10") Integer size) {
        IPage<Role> page = roleService.page(new Page<>(current, size)); // 接口引用
        return ResponseEntity.ok(page);
    }

    @RequestMapping("/list")
    public List<Role> list() {
        return roleService.list();
    }

    @GetMapping("/search")
    public Optional<Object> search(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword
    ) {
        Page<Role> page = new Page<>(pageNum, pageSize);
        return roleService.search(page, new LambdaQueryWrapper<Role>()
                .like(Role::getName, keyword)
                .or()
                .like(Role::getDescription, keyword)
                .or()
                .like(Role::getRoleKey, keyword));

    }

    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Role>> getRolesByUserId(@PathVariable Long userId) {
        return ResponseEntity.ok(roleService.getRolesByUserId(userId));
    }

    @GetMapping("/{id}")
    public ResponseEntity<Role> getRoleWithPermissions(@PathVariable Long id) {
        return ResponseEntity.ok(roleService.getRoleWithPermissions(id));
    }

    @PostMapping("/create")
    public Role createRole(@RequestBody Role entity) {
        // 检查角色是否存在
        if (roleService.getById(entity.getName()) != null) {
            throw new IllegalArgumentException("角色已存在！");
        }
        roleService.save(entity);
        return entity;
    }

    @PostMapping("/update")
    public Role updateRole(@RequestBody Role entity) {
        // 检查角色是否存在
        if (roleService.getById(entity.getId()) == null) {
            throw new IllegalArgumentException("角色不存在！");
        }
        roleService.updateById(entity);
        return entity;
    }

    @PostMapping("/delete/{roleId}")
    public void  deleteRole(@PathVariable Long roleId) {
        // 检查角色是否存在
        if (roleService.getById(roleId) == null) {
            throw new IllegalArgumentException("角色不存在！");
        }
        roleService.removeById(roleId);
    }

    @PostMapping("/deleteBatch")
    public void  deleteRole(@RequestBody List<Long> roleIds) {
        // 检查角色是否存在
        List<Role> roles = roleService.listByIds(roleIds);
        if (roles.size() != roleIds.size()) {
            throw new IllegalArgumentException("角色有误，请检查！");
        }
        roleService.removeByIds(roleIds);
    }
    @GetMapping("/getPermission")
    public List<Permission> getPermissionsByRoleId(@RequestBody Long roleId) {
        return permissionService.getPermissionsByRoleId(roleId);
    }

    // 为角色分配权限
    @PostMapping("/assignPermissions")
    public void assignPermissions(
            @RequestParam Long roleId,
            @RequestParam List<Long> permissionIds
    ) {
        // 角色是否存在
        Role role = roleService.getById(roleId);
        if (role == null) {
            throw new IllegalArgumentException("角色不存在");
        }
        List<Permission> permissions = permissionService.listByIds(permissionIds);
        if (permissions.size() != permissionIds.size()) {
            throw new IllegalArgumentException("请检查权限后再操作");
        }
        roleService.assignPermissions(roleId, permissionIds);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> remove(@PathVariable Long id) {
        roleService.removeById(id);
        return ResponseEntity.noContent().build();
    }


}